package com.adam.framework.jdbc;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import junit.framework.TestCase;

public class ProxyTestCase extends TestCase {

	public void testUser() {
		User user = new MyUser();
		user.setUserName("dog");
		UserHandler handler = new UserHandler();
		user = handler.bind(user);

		assertEquals("Proxy dog", user.getUserName());
	}

	private class MyUser implements User {
		String userName = null;
		String email = null;

		public String getEmail() {
			return email;
		}

		public void setEmail(String email) {
			this.email = email;
		}

		public String getUserName() {
			return userName;
		}

		public void setUserName(String userName) {
			this.userName = userName;
		}
	}

	class UserHandler implements InvocationHandler {
		User user = null;

		public User bind(User user) {
			this.user = user;
			return (User) Proxy.newProxyInstance(user.getClass().getClassLoader(), user.getClass().getInterfaces(),
					this);
		}

		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			if ("getUserName".equals(method.getName())) {
				return "Proxy " + user.getUserName();
			} else {
				return method.invoke(user, args);
			}
		}
	}
}
